/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: HP
 * Date: 2023 -04 -11
 * Time: 16:50
 */
public class MyStringBuilder {
    private char[] str;
    private int cnt;

    public MyStringBuilder() {
    }

    public MyStringBuilder(String s) {
        str = s.toCharArray();
        cnt = str.length;
    }

    public MyStringBuilder append(MyStringBuilder s) {
        if (s == null || s.length() == 0) return this;
        char[] addStr = s.toString().toCharArray();
        //开辟空间+拷贝
        char[] newStr = new char[addStr.length + cnt];
        System.arraycopy(str, 0, newStr, 0, str.length);
        System.arraycopy(addStr, 0, newStr, str.length, addStr.length);
        str = newStr;
        cnt += s.length();
        return this;
    }

    public MyStringBuilder append(int i) {
        char[] newStr = new char[cnt + 1];
        System.arraycopy(str, 0, newStr, 0, cnt);
        newStr[cnt++] = (char) (i + '0');
        str = newStr;
        return this;
    }


    public int length() {
        return cnt;
    }

    public char charAt(int index) {
        if (index >= cnt) {
            throw new IndexOutOfBoundsException("index out of thr range!");
        }
        return str[index];
    }

    public MyStringBuilder toLowerCase() {
        MyStringBuilder ret = new MyStringBuilder();
        ret.str = new char[cnt];
        ret.cnt = cnt;
        for (int i = 0; i < cnt; i++) {
            if (str[i] >= 'A' && str[i] <= 'Z') ret.str[i] = (char) (str[i] - 'A' + 'a');
            else ret.str[i] = str[i];
        }
        return ret;
    }

    public MyStringBuilder subString(int begin, int end) {
        if (begin < 0 || end >= cnt || begin > end) {
            throw new RuntimeException("index error!");
        }
        MyStringBuilder ret = new MyStringBuilder();
        ret.str = new char[end - begin + 1];
        ret.cnt = str.length;
        int index = 0;
        for (int i = begin; i <= end; i++) {
            ret.str[index++] = str[i];
        }
        return ret;
    }

    public String toString() {
        return String.valueOf(str);
    }

}
